package com.df.happylearn.articles;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.df.happylearn.R;
import com.df.happylearn.articlecontent.ContentActivity;
import com.df.happylearn.model.ArticleInfo;
import com.df.happylearn.sqlite.DBUtil;
import com.df.happylearn.utils.Constants;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dingfeng on 2016/5/24.
 */
public class ArticlesFragment extends Fragment implements ArticlesContract.View {

    private Context mContext;
    RecyclerView mRecyclerView;
    SwipeRefreshLayout mRefreshLayout;
    View no_network_ui;
    TextView txtReferesh;
    private ArticleAdapter mAdapter;
    private List<ArticleInfo> mArticleList = new ArrayList<>();
    private LinearLayoutManager mLayoutManager;
    private ArticlesContract.Presenter mPresenter;
    private boolean isLoading = false;
    private int page = 0;

    public ArticlesFragment() {

    }

    public static ArticlesFragment newInstance() {
        return new ArticlesFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_articles, null);
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refreshLayout);
        mRefreshLayout.setOnRefreshListener(onRefreshListener);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addOnScrollListener(onScrollListener);

        mAdapter = new ArticleAdapter(mContext, mArticleList);
        mAdapter.setOnItemClickLitener(onItemClickLitener);
        mRecyclerView.setAdapter(mAdapter);

        no_network_ui = view.findViewById(R.id.no_network_ui);
        no_network_ui.setVisibility(View.GONE);
        txtReferesh = (TextView) view.findViewById(R.id.txtReferesh);
        txtReferesh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.loadArticles();
            }
        });
    }

    private void initData() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshLayout.setRefreshing(true);
                mPresenter.start();
            }
        }, Constants.INIT_CONTENT_DELAYED);
    }

    RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            setRefreshEnable(mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0);
            if (!isLoading && mAdapter != null && mLayoutManager.findLastVisibleItemPosition() == mAdapter.getItemCount() - 1) {
                isLoading = true;
                loadMore();
            }
        }
    };

    ArticleAdapter.OnItemClickListener onItemClickLitener = new ArticleAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            ArticleInfo articleInfo = mArticleList.get(position);
            Intent intent = new Intent(mContext, ContentActivity.class);
            intent.putExtra("articleId", articleInfo.mId);
            if (articleInfo.isread == 1) {
                startActivity(intent);
            } else {
                startActivityForResult(intent, Constants.MAINACTIVITY_REQUEST_CODE);
            }
        }
    };

    SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mPresenter.loadArticles();
        }
    };

    private void setRefreshEnable(boolean isRefreshEnable) {
        mRefreshLayout.setEnabled(isRefreshEnable);
    }

    private void showNoNetworkView() {
        no_network_ui.setVisibility(View.VISIBLE);
        mRefreshLayout.setVisibility(View.GONE);
    }

    private void hideNoNetworkView() {
        no_network_ui.setVisibility(View.GONE);
        mRefreshLayout.setVisibility(View.VISIBLE);
    }

    // 加载更多
    private void loadMore() {
        page = mArticleList.size() / ArticlesPresenter.limit;// 计算得出当前的请求页
        mPresenter.loadArticles(page);
    }

    @Override
    public void setPresenter(ArticlesContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showArticles(List<ArticleInfo> articles) {
        if (articles != null && articles.size() > 0) {
            mArticleList.clear();
            mArticleList.addAll(articles);
            mAdapter.notifyDataSetChanged();
        }
        hideNoNetworkView();
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void showMore(List<ArticleInfo> articles) {
        mArticleList.addAll(articles);
        mAdapter.notifyDataSetChanged();
        isLoading = false;
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void showNoArticles() {
        showNoNetworkView();
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.MAINACTIVITY_REQUEST_CODE && resultCode == Constants.ACTICLEACTIVITY_RESULT_CODE && data != null) {
            int articleId = data.getIntExtra("article_id", -1);
            for (ArticleInfo item : mArticleList) {
                if (item.mId == articleId) {
                    item.isread = 1;
                    mAdapter.notifyDataSetChanged();
                    DBUtil.getInstance().getArticleDao().update(item);
                    break;
                }
            }
        }
    }
}
